/* eslint-disable react-hooks/exhaustive-deps */
import { XoProTable } from '@/components/XoProTable'
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, message, Space, Checkbox, Tooltip } from 'antd';
import { ProFormSelect, ProFormTextArea } from '@ant-design/pro-form';
import styles from './index.less'
import React, { useEffect, useState } from 'react'
import { history, Link } from 'umi';
import { getgroupOption } from '@/services/student';
import {
  DrawerForm, ModalForm
} from '@ant-design/pro-form';
import { getWarnList, getWarnRecordFollow } from '@/services/warning';
import { handleTime, ruleType } from '../../components/Exercises';
import StudentInfo from '../../StudentInfo';
import { useRef } from 'react';
import { getAddRecords } from '@/services/records';
import { onRequestNickName } from '@/utils/requestPhone';
import { courseItemExport } from '@/services/situation';
import moment from 'moment';

interface Pramas {
  current?: string,
  changeCount: () => void
}
export default function WaitFollow(props: Pramas) {
  const [shiwForm, setShowForm] = useState<boolean>(false);
  const [idx, setIndex] = useState<number>();
  const { current, changeCount } = props;
  const [ids, setUserId] = useState<any>();
  const [ids3, setId] = useState<any>();
  const { id } = history.location.query || {}
  const [option, setGroupOption] = useState<any>()
  const [type, setType] = useState<any>()
  const [loading, setLoading] = useState<boolean>(false)
  const [visi, setVisible] = useState<boolean>(false)
  const [optionItem, setOptionValue] = useState<any>()
  const [phoneValue, setPhoneValue] = useState<any>()
  const [uid, setUid] = useState<any>()
  const [list, setWarning] = useState<any>()

  const ref = useRef<ActionType>()
  useEffect(() => {

    (async () => {
      const res = await getgroupOption({ activityId: id, pageSize: -1 })
      const res1 = res?.result?.map((item: any) => {
        return { label: item.name, value: item.id }
      })
      setGroupOption(res1)
    })()
  }, [])
  const handleOnChange = async (record: any) => {
    const res = await getWarnRecordFollow({ id: record?.id });
    if (res.success) {
      changeCount()
      ref.current?.reload();
    }

  }
  // const goChess = (record: any) => {
  //   const w = window.open('_black');
  //   w!.location.href = `/course/chess?id=${record.uid}`
  // }
  // const gonNewPage = () => {
  //   const w = window.open('_black');
  //   w!.location.href = "/add"
  // }

  const showForm = async (re: any, index: number) => {
    setIndex(index)
    setShowForm(true);
  }
  const onReset = () => {
    setType('')
    setOptionValue('')
    setPhoneValue('')
  }
  const columns: ProColumns[] = [
    current == '1' ? {
      title: '跟进',
      dataIndex: 'x',
      search: false,
      ellipsis: true,
      width: 50,
      render: (_, record) => {
        return (
          <Checkbox
            key={record.id}
            disabled={loading}
            onChange={async () => {
              setLoading(true);
              await handleOnChange(record);
              setLoading(false);
            }}
          />
        );
      }
    } : {
      hideInTable: true, search: false,
    },
    {
      title: '用户昵称',
      dataIndex: 'nickname',
      search: false,
      ellipsis: true,
      align: 'center',
      render: (text, record, index) => (
        <a onClick={() => showForm(record, index)}>{record?.nickname || '-'}</a>
      )
    },
    {
      dataIndex: 'nicknamePhone',
      hideInTable: true,
      title: '昵称/手机号',
      ellipsis: true,
      align: 'center',
      renderFormItem: () => {
        return (
          <div >
            <ProFormSelect
              wrapperCol={{ span: 24 }}
              labelCol={{ span: 24 }}
              name="uid"
              showSearch
              labelAlign="left"
              debounceTime={500}
              placeholder="请选择"
              fieldProps={{
                onChange: (val) => setPhoneValue(val)
              }}
              request={onRequestNickName}
            />
          </div>
        );
      },
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      search: false,
      ellipsis: true,
      align: 'center'

    },
    {
      title: '手机号',
      dataIndex: 'phone',
      ellipsis: true,
      search: false,
      align: 'center',
    },
    {
      title: '班级',
      dataIndex: 'groupName',
      valueType: 'select',
      ellipsis: true,
      align: 'center',
      renderFormItem: () => {
        return (
          <div className={styles.search}>
            <ProFormSelect
              wrapperCol={{ span: 24 }}
              labelCol={{ span: 24 }}
              fieldProps={{
                onChange: (val) => setOptionValue(val)
              }}
              name="groupId"
              labelAlign="left"
              placeholder="请选择"
              options={option}
            />
          </div>
        );
      },
    },
    {
      title: '辅导老师',
      dataIndex: 'teacherName',
      ellipsis: true,
      search: false,
      align: 'center'

    },
    current == '2' || current == '3' || current == '4' ? {
      title: '跟进时间',
      dataIndex: 'followTime',
      ellipsis: true,
      search: false,
      align: 'center',
    } :
      {
        hideInTable: true,
        search: false,

      },
    {
      title: '预警详情',
      dataIndex: '',
      width: '200px',
      ellipsis: true,
      search: false,
      align: 'center',
      render: (text, record: any) => (
        <Tooltip arrowPointAtCenter placement="top" title={
          record?.warningRole ?
            `${record?.warningRole?.timeLimit && record?.warningRole?.timeLimit != 0 ? record?.warningRole?.timeLimit : ''}
            ${handleTime(record?.warningRole?.timeUnit || '') || ''}
            ${ruleType(record?.warningRole?.ruleType || "") || ''}
            ${record?.warningRole?.ruleType == 6 || record?.warningRole?.ruleType == 5 || record?.warningRole?.ruleType == 12 || record?.warningRole?.ruleType == 13 || record?.warningRole?.ruleType == 16 || record?.warningRole?.ruleType == 17 ? '' : record?.warningRole?.compareType ? record?.warningRole?.compareType == 1 ? "高于" : "低于" : ""}
            ${record?.warningRole?.value || ''}
            ${record?.warningRole?.ruleType && record?.warningRole?.ruleType != 17 ? record?.warningRole?.ruleType == 1 || record?.warningRole?.ruleType == 2 || record?.warningRole?.ruleType == 3 || record?.warningRole?.ruleType == 9 || record?.warningRole?.ruleType == 10 ? "%预警" : "局预警" : ""}
        `: ""

        }>
          {

            record?.warningRole ? <span style={{ color: record?.type == 1 ? 'red' : "green" }}>{
              `${record?.warningRole?.timeLimit && record?.warningRole?.timeLimit != 0 ? record?.warningRole?.timeLimit : ''}${handleTime(record?.warningRole?.timeUnit || '') || ''}${ruleType(record?.warningRole?.ruleType || "") || ''}${record?.warningRole?.ruleType == 6 || record?.warningRole?.ruleType == 5 || record?.warningRole?.ruleType == 17 ? '' : record?.warningRole?.compareType == 1 ? "高于" : "低于"}${record?.warningRole?.ruleType == 17 ? record?.warningRole?.gradeName : record?.warningRole?.value}
          ${record?.warningRole?.ruleType && record?.warningRole?.ruleType != 17 ? record?.warningRole?.ruleType == 1 || record?.warningRole?.ruleType == 2 || record?.warningRole?.ruleType == 3 || record?.warningRole?.ruleType == 9 ? "%预警" : "局预警" : ""}
          `
            }</span> : '-'

          }
        </Tooltip>
      )
    },
    {
      title: '预警类型',
      dataIndex: 'type',
      ellipsis: true,
      align: 'center',
      valueType: 'select',
      fieldProps: {
        onChange: (val: any) => setType(val)
      },
      valueEnum: {
        0: '全部',
        1: '未完成预警',
        2: '达标预警'
      },
      render: (text, record) => {
        return <span>{record.type == 2 ? '达标预警' : '未完成预警'}</span>
      }
    },
    {
      title: '预警时间',
      dataIndex: 'createTime',
      search: false,
      ellipsis: true,
      align: 'center',


    },
    {
      title: '悟空战力',
      dataIndex: 'gokuCurPower',
      search: false,
      ellipsis: true,
      align: 'center',
    },
    current == '2' || current == '3' || current == "4" ? {
      title: '完成条件',
      dataIndex: 'completeRole',
      search: false,
      ellipsis: true,
      align: 'center',
      render: (_, record) => (
        <Tooltip arrowPointAtCenter placement="top" title={record?.completeRole ? `${record?.completeRole?.timeLimit || ''}${handleTime(record?.completeRole?.timeUnit || '')}${ruleType(record?.completeRole?.ruleType || '')}${record?.completeRole?.ruleType == 6 || record?.completeRole?.ruleType == 5 || record?.completeRole?.ruleType == 12 || record?.completeRole?.ruleType == 13 || record?.completeRole?.ruleType == 16 ? "" : record?.completeRole?.compareType ? record?.completeRole?.compareType == 1 ? "高于" : "低于" : ''}${record?.completeRole?.value || ''}
        ${record?.completeRole?.ruleType ? record?.completeRole?.ruleType == 1 || record?.completeRole?.ruleType == 2 || record?.completeRole?.ruleType == 3 || record?.completeRole?.ruleType == 9 || record?.completeRole?.ruleType == 10 ? "%完成" : "局预警" : ""}
        ` : null}>
          {

            record?.completeRole ?
              <span>
                {
                  `${record?.completeRole?.timeLimit || ''}${handleTime(record?.completeRole?.timeUnit || '')}${ruleType(record?.completeRole?.ruleType || '')}${record?.completeRole?.ruleType == 6 || record?.completeRole?.ruleType == 5 || record?.completeRole?.ruleType == 12 || record?.completeRole?.ruleType == 13 || record?.completeRole?.ruleType == 16 ? "" : record?.completeRole?.compareType ? record?.completeRole?.compareType == 1 ? "高于" : "低于" : ""}${record?.completeRole?.value || ''}
            ${record?.completeRole?.ruleType ? record?.completeRole?.ruleType == 1 || record?.completeRole?.ruleType == 2 || record?.completeRole?.ruleType == 3 || record?.completeRole?.ruleType == 9 || record?.completeRole?.ruleType == 10 ? "%完成" : "局预警" : ""}
            `
                }
              </span> : '-'
          }
        </Tooltip>
      )
    } : {
      hideInTable: true, search: false,
    },
    current == '3' ? {
      title: '完成类型',
      dataIndex: 'completeType',
      search: false,
      ellipsis: true,
      align: 'center',
      render: (text, record) => (
        <span>{record?.completeType == 1 ? '跟进完成' : record?.completeType == 2 ? '主动完成' : "-"}</span>
      )

    } : {
      hideInTable: true, search: false,
    },
    current == '3' ? {
      title: '完成时间',
      dataIndex: 'completeTime',
      search: false,
      ellipsis: true,
      align: 'center',


    } : {
      hideInTable: true, search: false,
    },
    current == '4' ? {
      title: '结束时间',
      dataIndex: 'endTime',
      search: false,
      ellipsis: true,
      align: 'center',

    } : {
      hideInTable: true, search: false,
    },
    {
      title: '操作',
      dataIndex: '',
      search: false,
      fixed: 'right',
      align: 'center',
      ellipsis: true,
      render: (text, record: any, index) => {
        const rule = record?.warningRole?.ruleType
        return <Space key={index}>
          {
            rule == 3 || rule == 4 || rule == 5 || rule == 6 || rule == 7 || rule == 8 ?
              <Link key="one" to={`/course/chess?id=${record?.uid}&courseId=${id}`} target="_blank">
                <a>查看棋谱</a>
              </Link> : null
          }
          <a onClick={() => { setVisible(true); setUid(record?.uid) }}>添加沟通记录</a>
        </Space>
      }
    },
  ]

  // 导出
  const exportList = async () => {
    const params = {
      groupId: optionItem,
      activityId: id,
      state: current,
      type: type,
      uid: phoneValue
    }
    if (list?.length == 0) {
      message.destroy();
      message.error('没有可导出的数据')
      return;
    }
    setLoading(true);
    await courseItemExport({
      exportType: 'exportWarningRecords',
      map: {
        ...params
      },
      fileName: `学情预警 ${moment(new Date()).format('YYYY-MM-DD HH时mm分ss秒')}.xlsx`
    });
    setLoading(false);
  }

  return (

    <div>
      <XoProTable
        columns={columns}
        className={styles.table}
        scroll={{ x: 1600 }}
        rowKey="key"
        params={{
          state: current,
        }}
        actionRef={ref}

        onReset={onReset}
        request={async (params: any) => {
          if (type != 0) {
            params['type'] = type
          } else {
            delete params.type
          }
          const res = await getWarnList({
            ...params,
            uid: phoneValue,
            groupId: optionItem,
            activityId: id,
          });
          const ids1 = res?.result?.records?.map((item: any) => {
            return item.uid
          })
          const ids2 = res?.result?.records?.map((item: any) => {
            return item.activityUserId
          })
          setUserId(ids1)
          setId(ids2)
          setWarning(res?.result?.records)
          return {
            data: res?.result?.records,
            total: res?.result?.total
          }
        }}
        hasIndex={false}
        toolBarRender={() => [
          <Button key="export" loading={loading} onClick={exportList}>导出
          </Button>,
        ]}

      />
      <DrawerForm
        className={styles.drawer_form}
        visible={shiwForm}
        width="80%"
        drawerProps={{
          footerStyle: { display: 'none' }, closeIcon: false, bodyStyle: { padding: '0' }, onClose: () => ref.current?.reload()
          , destroyOnClose: true
        }}
        onVisibleChange={(val) => setShowForm(val)}
      >
        <StudentInfo ids={ids} idx={idx} ids3={ids3} />
      </DrawerForm>
      <ModalForm
        title='添加沟通记录'
        submitter={{
          searchConfig: {
            submitText: '确认',
            resetText: '取消',
          },
        }}
        modalProps={{
          destroyOnClose: true
        }}
        onVisibleChange={(val) => setVisible(val)}
        layout="horizontal"
        visible={visi}
        onFinish={async (values) => {

          const res = await getAddRecords({
            ...values, courseId: id, uid: uid
          })
          if (res.success) {
            message.success('添加成功')
            setVisible(false);
          }

        }}
      >
        <div style={{ width: '50%', margin: 'auto' }}>
          <ProFormSelect
            name="object"
            label="沟通对象"
            width="md"
            fieldProps={{
              // onChange: (val) => handleChange(val)
            }}
            initialValue={'0'}
            params={{

            }}
            valueEnum={{
              0: '请选择',
              1: "爸爸",
              2: "妈妈",
              3: "爷爷",
              4: "奶奶",
              5: "姥姥",
              6: "姥爷",
              7: "其他",
            }}
            rules={[
              { required: true, message: '请选择沟通对象' },
              { pattern: /^[1-9]$/, message: '请选择沟通对象' }
            ]}
          />
          <ProFormSelect
            name="purpose"
            label="沟通目的"
            width="md"
            fieldProps={{
              // onChange: (val) => handleChange(val)
            }}
            initialValue={'0'}
            params={{

            }}
            valueEnum={{
              0: '请选择',
              1: "日常沟通",
              2: "续报沟通",
              3: "退费沟通",
              4: "特殊情况沟通",
            }}
            rules={[
              { required: true, message: '请选择沟通目的' },
              { pattern: /^[1-9]$/, message: '请选择沟通目的' }
            ]}
          />
          <ProFormTextArea
            name="content"
            label="沟通内容"
            placeholder="请输入名称"
            fieldProps={{
              showCount: true, maxLength: 500, placeholder: "请输入沟通内容",
            }}
            rules={[{ required: true, message: '请输入沟通内容' }]}
          />
        </div>
      </ModalForm>
    </div>
  )
}
